# -*- coding: utf-8 -*-


"""
Game loading screen.

Button "Load" -> screen "Players order".

Need:
    - Nothing
Changes:
    - All gamestate
"""

import urllib2
import socket

from kivy.logger import Logger
from kivy.properties import StringProperty

from model.gamestate import Phase
from ui.hat_widget import HatWidget, open_ok_popup
from model.json_loader import JsonLoader
from constants import MAX_PIN_LENGTH, MIN_PIN_LENGTH


class LoadGameScreen(HatWidget):
    game_id = StringProperty()
    pin_code = StringProperty()
    """ Drawing screen which will be used for loading a game
    """

    def __init__(self, game_state, presenter, **kwargs):
        self.HOST = presenter.settings.game.server_name
        super(LoadGameScreen, self).__init__(presenter, **kwargs)
        self.game_state = game_state
        self.game_id = u''
        self.pin_code = u''
        self.input_id.focus = True
        self.load_button.enabled = False
        self.is_correct_id = False
        self.is_correct_pin = False

    def on_load_pressed(self):
        """ Called when button "Load" is pressed". Load gamestate by id.

            loads json with gamestate from
            <HOST>/game_template_json?game_id=<game_id>&pin=<pin_code>
            changes phase to PLAYERS_ORDER
        """
        loader = JsonLoader()
        try:
            Logger.debug('on_load_pressed(): sending request: game_id: ' +
                         str(self.input_id.text) + ' , pin: ' +
                         str(self.input_pin.text))
            self.presenter.game_state = loader.load_game_from_url(
                self.HOST + '/game_template_json?game_id=' +
                self.input_id.text +
                '&pin=' + self.input_pin.text)
            self.game_state = self.presenter.game_state
            self.game_state.pin_code = int(self.input_pin.text)
            self.game_state.is_game_host = True
        except urllib2.HTTPError as msg:
            if msg.code == 404:
                error_text = _('Game not found.\nCheck you game-id')
            elif msg.code == 403:
                error_text = _('Incorrect PIN number')
            elif msg.code == 424:
                error_text = _('Specified game cannot be loaded')
            else:
                error_text = _('Network error')
            open_ok_popup(_('Error'), error_text, self)
            return
        except urllib2.URLError as msg:
            Logger.debug('on_load_pressed(): URLError: %s' % msg.reason)
            open_ok_popup(_('Error'), _('Network error'), self)
            return
        except urllib2.socket.timeout:
            open_ok_popup(_('Error'), _('Network error'), self)
            return
        except:
            open_ok_popup(_('Error'), _('Unknown error'), self)
            return

        self.presenter.change_phase(Phase.START_GAME)

    def go_back(self):
        self.game_state.clear()
        self.presenter.change_phase(Phase.WELCOME)

    def check_id(self):
        self.is_correct_id = self.input_id.text.isdigit()
        self.load_button.enabled = (self.is_correct_id and
                                    self.is_correct_pin)

    def check_pin(self):
        self.is_correct_pin =\
            (self.input_pin.text.isdigit() and
             len(self.input_pin.text) <= MAX_PIN_LENGTH
             and len(self.input_pin.text) >= MIN_PIN_LENGTH)
        self.load_button.enabled = (self.is_correct_id and self.is_correct_pin)

    def try_go_next(self):
        if self.load_button.enabled:
            self.on_load_pressed()
